package net.sunbeta.test.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class MailSenderHelper {

	public void sentEmail(final Map model) {
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost("mailhost.uk.nomura.com");

		MimeMessagePreparator mimepreparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
				message.setTo(new String[] { "beam.sun@nomura.com", "sunxboy@gmail.com" });
				message.setFrom("email@nomura.com");
				message.setSubject("test email report");
				String mailContent = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), "mail-template.vm", model);
				message.setText(mailContent);
				// message.addAttachment(eccsFileName, new File(""));
			}

		};
		mailSender.send(mimepreparator);
	}
	
	public VelocityEngine getVelocityEngine() throws Exception {
		/* first, get and initialize an engine */  
        VelocityEngine ve = new VelocityEngine();   
        Properties properties = new Properties();   
        properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init(properties);   
        //Template t= ve.getTemplate("vm.vm");   
        //VelocityContext context = new VelocityContext();   
        //context.put("name", "DingDangXiaoMa");   
        //context.put("site", "http://www.sun.com");   
        //StringWriter writer = new StringWriter();   
        //t.merge(context, writer);   
        //System.out.println(writer.toString());   
        return ve;
	}
	
	public static void main(String[] args) throws Exception{
		MailSenderHelper helper = new MailSenderHelper();
		Map mailMap = new HashMap<String,String>();
		mailMap.put("name", "sunxboy");
		
		helper.sentEmail(mailMap);
		System.out.println("email has sent successfully.");
	}
}
